package com.example.springsecurity.controller;

import com.example.springsecurity.common.Result;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
 
@Slf4j
@RestController
@RequestMapping("/minio")
@Api(value = "文件模块", tags = "文件模块")
public class MinioController {
    @Autowired
    private MinioClient minioClient;
 
    private static final String MINIO_BUCKET = "news";
    private static final String BASE_URL="http://kin.qinsy.ltd:9080/"+MINIO_BUCKET+"/";

    @ApiOperation("上传")
    @PostMapping("/upload")
    public Result<?> upload(@RequestParam(name = "file", required = false) MultipartFile[] file){
        if (file == null || file.length == 0) {
            return  Result.error("500","上传文件不能为空");
        }
        List<String> orgfileNameList = new ArrayList<>(file.length);
 
        for (MultipartFile multipartFile : file) {
            String timeStr = (new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date());
            String orgfileName = timeStr+"_"+multipartFile.getOriginalFilename();
            orgfileNameList.add(BASE_URL+orgfileName);
 
            try {
                InputStream in = multipartFile.getInputStream();
                minioClient.putObject(MINIO_BUCKET, orgfileName, in, new PutObjectOptions(in.available(), -1));
                in.close();
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.error("500","上传失败");
            }
        }
 
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("fileUrl", orgfileNameList);
        return Result.success(data);
    }

    @ApiOperation("删除")
    @DeleteMapping("/delete")
    public Result<?> delete(@RequestParam String fileName) {
        try {
            minioClient.removeObject(MINIO_BUCKET, fileName);
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error("500","删除失败");
        }
        return Result.success();
    }

}